import IComponentServer from "../IComponentServer";
import { imStore } from "@/store/imStore";
import { userData } from "@/store/userData";
import { getGroupProfile } from "@/hooks/imHooks";
import { restartIm } from "@/hooks/imLogin"

let firstWait = true;

const wait = (time) => {
  return new Promise((resolve, reject) => {
    if (!time) {
      resolve(true);
    } else {
      setTimeout(() => {
        resolve(true);
      }, time);
    }
  });
};

/**
 * class TUIConversationServer
 *
 * TUIConversation 逻辑主体
 */
export default class TUIConversationServer extends IComponentServer {
  public TUICore: any;
  public imStore: any = imStore();
  constructor(TUICore: any) {
    super();
    this.TUICore = uni.$TUIKit;
    uni.setStorageSync(`TIM_${uni.$chat_SDKAppID}_isTUIKit`, true);
    this.bindTIMEvent();
    uni.$once("SDKReady", () => {
      this.getConversationList();
    });
  }

  /**
   * /////////////////////////////////////////////////////////////////////////////////
   * //
   * //                                    TIM 事件监听注册接口
   * //
   * /////////////////////////////////////////////////////////////////////////////////
   */

  private bindTIMEvent() {
    this.TUICore.on(
      uni.$TIM.EVENT.CONVERSATION_LIST_UPDATED,
      this.handleConversationListUpdate
    );
  }

  private unbindTIMEvent() {
    this.TUICore.off(
      uni.$TIM.EVENT.CONVERSATION_LIST_UPDATED,
      this.handleConversationListUpdate
    );
  }

  public handleConversationListUpdate = async (res: any) => {
    //uni.$tm.u.debounce(()=>{
    //uni.hideLoading();
	/*
    console.log("handleConversationListUpdate");
    console.log("handleConversationListUpdate");
    console.log("handleConversationListUpdate");
    console.log("handleConversationListUpdate");
    console.log("handleConversationListUpdate");
    console.log(res);
	*/
    //const res = JSON.parse(JSON.stringify(result));

    

    let needRefestAddGroupList = false;

    if (res.data.length === 0) {
      console.log("暂无回话哦～");
    }
    const USER_DATA = userData();
    const arr = res.data.filter((item: any) => {
    //   if (item.lastMessage.time) {
    //     item.lastMessage.time1 = item.lastMessage.time;
    //   }

      if (
        item.lastMessage.type === "TIMGroupSystemNoticeElem" &&
        item.lastMessage.payload.operationType === 1 &&
        item.lastMessage.payload.groupProfile.to === USER_DATA.id
      ) {
        needRefestAddGroupList = true;
      }
      if(item.conversationID==='@TIM#SYSTEM'){
            return false;
      }
      return true;

      

    });

    if (needRefestAddGroupList) {
        // console.log('emit updateAddGroupList')
        // console.log('emit updateAddGroupList')
        // console.log('emit updateAddGroupList')
         uni.$emit("updateAddGroupList");
    }

    uni.$emit("groupProfileUpdate");

    // arr.sort((a: any, b: any) => {
    //   return Number(b.lastMessage.time1) - Number(a.lastMessage.time1);
    // });
    // arr.sort((a: any, b: any) => {
    //   return Number(b.isPinned) - Number(a.isPinned);
    // });
    const IM_STORE: any = imStore();
    IM_STORE.setConversationList(arr);
  };

  /**
   * 组件销毁
   *
   */
  public destroyed() {
    this.unbindTIMEvent();
  }

  /*
   * 获取 conversationList
   *
   * @returns {Promise}
   */
  public async getConversationList() {
    return new Promise<void>(async (resolve, reject) => {
		
      try {
        const imResponse = await uni.$TUIKit.getConversationList();
        const IM_STORE: any = imStore();

        //IM_STORE.setConversationList(imResponse.data.conversationList);
        await wait(500);
        for (let i = 0; i < IM_STORE.conversationList.length; i++) {


          const item = IM_STORE.conversationList[i];
          const index = i;
          if (item.type === "GROUP") {
            await wait(500);
            const profile = await getGroupProfile(item.groupProfile.groupID);
			/*
            console.log('profile')
            console.log('profile')
            console.log('profile')
            console.log(profile)
			*/
            IM_STORE.updateConversationListGroupProfile({
              value: profile.data.group,
            });
          }
        }

        uni.$emit('conversationGroupUpdated')
        //uni.hideLoading();
        resolve(imResponse);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 获取 conversationList
   *
   * @param {string} conversationID 会话ID
   * @returns {Promise}
   */
  public async getConversationProfile(conversationID: string) {
    return new Promise<void>(async (resolve, reject) => {
      try {
        const imResponse = await this.TUICore.getConversationProfile(
          conversationID
        );
        resolve(imResponse);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 删除会话
   *
   * @param {string} conversationID 会话ID
   * @returns {Promise}
   */

  public async deleteConversation(conversationID: string) {
    return new Promise<void>(async (resolve, reject) => {
      try {
        const imResponse: any = await this.TUICore.deleteConversation(
          conversationID
        );
        resolve(imResponse);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 置顶会话
   *
   * @param {Object} options 置顶参数
   * @returns {Promise}
   */
  public async pinConversation(options: any) {
    return new Promise<void>(async (resolve, reject) => {
      try {
        const imResponse: any = await this.TUICore.pinConversation(options);
        resolve(imResponse);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * C2C消息免打扰
   *
   * @param {Object} options 消息免打扰参数
   * @returns {Promise}
   */
  public async muteConversation(options: any) {
	  
    return new Promise<void>(async (resolve, reject) => {
      try {
        const imResponse: any = await this.TUICore.setMessageRemindType(
          options
        );
        resolve();
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 设置已读
   *
   * @param {string} conversationID 会话ID
   * @returns {Promise}
   */
  public async setMessageRead(conversationID: string) {
    return new Promise<void>(async (resolve, reject) => {
      try {
        const imResponse: any = await this.TUICore.setMessageRead({
          conversationID,
        });
        resolve(imResponse);
      } catch (error) {
        //console.log(error);
        // restartIm();
        reject(error);
      }
    });
  }
}
